package cheme.ProcessEditor.Tools;

import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.gef.SharedCursors;
import org.eclipse.gef.requests.CreationFactory;
import org.eclipse.gef.tools.ConnectionCreationTool;

import cheme.ProcessModel.ProcessModel;
import cheme.ProcessModel.Subprocess.Subprocess;

public class StreamCreationTool extends ConnectionCreationTool
{
	private static boolean ENFORCE_MIN_LENGTH = false; //Flag indicates whether short streams will not be created
	private static int MIN_DELTA = 250; //The threshold for ignored streams
	private boolean allowCreation = false; //indiviual allow-creation flag
	
	public StreamCreationTool()
	{
		super();
		setUnloadWhenFinished(true);
	}

	public StreamCreationTool(CreationFactory factory)
	{
		super(factory);
		setUnloadWhenFinished(true);
	}
	
	protected static boolean getEnforceMinStreamLength()
	{
		return ENFORCE_MIN_LENGTH;
	}

	protected static void setEnforceMinStreamLength(boolean enforce_min_length)
	{
		ENFORCE_MIN_LENGTH = enforce_min_length;
	}

	protected static int getMinDelta()
	{
		return MIN_DELTA;
	}

	protected static void setMinDelta(int min_delta)
	{
		MIN_DELTA = min_delta;
	}

	protected boolean handleButtonDown(int button)
	{
		super.handleButtonDown(button);
		
		allowCreation = false;

		if(isInState(STATE_CONNECTION_STARTED))
		{
			// Fake a drag to cause feedback to be displayed immediately on
			// mouse down.
			handleDrag();
		}
		
		return true;
	}
	
	
	
	@Override
	protected boolean handleDragInProgress()
	{
		boolean valid = true;
		
		Dimension delta = getDragMoveDelta();
		double distance = Math.sqrt(Math.pow(delta.width, 2) + Math.pow(delta.height, 2)); 
		if(ENFORCE_MIN_LENGTH == true && distance <= MIN_DELTA)
		{
			valid = false;
		}
		
		boolean result = super.handleDragInProgress();
		
		Object o = getTargetEditPart().getModel();
		if(!(o instanceof ProcessModel) && !(o instanceof Subprocess))
		{
			valid = true;
		}
		
		if(!valid)
		{
			allowCreation = false;
			setCursor(SharedCursors.CURSOR_PLUG_NOT);
		}
		else
		{
			allowCreation = true;
		}
		
		return result;
	}

	protected boolean handleButtonUp(int button)
	{
		boolean result = true;
		
		if(false == allowCreation)
		{
			eraseSourceFeedback();
			eraseTargetFeedback();
			setState(STATE_INITIAL);
			handleFinished();
		}
		
		if(button == 1 && stateTransition(STATE_CONNECTION_STARTED, STATE_TERMINAL))
		{
			result = handleCreateConnection();
			handleFinished();
		}

		calculateCursor();
		
		return result;
	}
}
